package com.zjun.demo.experimentaldemo.gallery_monitoring

import android.content.Intent
import android.content.Intent.ACTION_PICK
import android.database.ContentObserver
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.provider.MediaStore
import android.util.Log
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import com.orhanobut.logger.Logger
import com.zjun.demo.experimentaldemo.R
import com.zjun.demo.experimentaldemo.base.BaseActivity
import com.zjun.demo.experimentaldemo.databinding.ActivityGalleryMonitoringBinding

/**
 * 监听图片增加或者删除
 */
class GalleryMonitoringActivity : BaseActivity<ActivityGalleryMonitoringBinding>() {

    val pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
        // Callback is invoked after the user selects a media item or closes the
        // photo picker.
        if (uri != null) {
            Log.d("PhotoPicker", "Selected URI: $uri")
        } else {
            Log.d("PhotoPicker", "No media selected")
        }
    }

    private val mContentObserver: ContentObserver = object : ContentObserver(Handler(Looper.getMainLooper())) {

        override fun onChange(selfChange: Boolean, uri: Uri?) {
            super.onChange(selfChange, uri)
            Logger.i("图片发生变化,$uri,selfChange = $selfChange")
        }

    }

    override fun initialize() {
        registerContentObserver()
    }

    override fun getLayoutId(): Int = R.layout.activity_gallery_monitoring

    fun insertVideo(view: View) {
        val intent =  Intent(ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent,1)
    }

    fun deleteVideo(view: View) {

    }

    fun deleteImage(view: View) {

    }

    fun insertImage(view: View) {

    }

    private fun registerContentObserver(){
        contentResolver.registerContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,true,mContentObserver)
    }

    override fun onDestroy() {
        super.onDestroy()
        contentResolver.unregisterContentObserver(mContentObserver)
    }

}